package com.gs.tests.seleniumextjs;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.annotations.*;

public class ArrayGrid {
	
	private WebDriver driver;
	private String testfile;
		
    @BeforeTest
	@Parameters({"browser","baseurl","testfile"})
	public void beforeTest(String browser, String url, String file)
    {
		driver = Utils.getDriverInstance(browser);
    	driver.get(url);
    	testfile = file;  
    	Utils.maximizeWindow(driver);
    }  
    
   @AfterTest
   public void afterTest()
   {
	   driver.quit();
   }
   
   @DataProvider(name = "CompanyData")      
   public Object[][] createData() throws Exception {
	   Object[][] retObjArr = Utils.getTestData(testfile);
       return retObjArr;
   }
   
   @Test(dataProvider = "CompanyData")
   private void actionOnCompany(String company, String action) throws InterruptedException 
   {
	   // get grid view for scrolling action
	   WebElement gridView = driver.findElement(By.xpath("//tbody[contains(@id,'gridview')]"));
	   new Actions(driver).moveToElement(gridView);
	   
	   // get all rows
	   List<WebElement> gridRows = driver.findElements(By.xpath("//tr[contains(@id,'gridview')]"));	   
	   
	   // move to testing row
	   WebElement selectedRow = null;
	   for (WebElement row:gridRows) 
	   {
 		    if (!row.isDisplayed()) {
			    gridView.sendKeys(Keys.ARROW_DOWN);		   		  
			    Thread.sleep(100);
		    } 
	   		row.click();
	   		
	   		// stop when find out the company
	   		if (row.getText().contains(company)) {
	   			selectedRow = row;
	   			break;
	   		}
	   }
	   
	   // stop if the company does not exist in the grid
	   Assert.assertNotNull(selectedRow);
	   
	   // switch between actions
	   int index = 1;
	   String message = "";	   
	   switch (action.toLowerCase()) {			
		case "sell": 
			index = 1;
			message = "Sell " + company;
			break;
		case "buy": 
			index = 2;
			message = "Buy " + company;
			break;		
		case "hold": 
			index = 2;
			message = "Hold " + company;
			break;		
		default: 
			// do nothing
	   }
	   
	   // click Action icon
	   String path = "td[last()]/div/img[" + index + "]";
	   WebElement actionIcon = selectedRow.findElement(By.xpath(path));
	   Assert.assertNotNull(actionIcon);
	   actionIcon.click();
	   Thread.sleep(500);

	   // verify data on popup dialog
	   path = "//div[contains(@id, 'messagebox') and contains(text(),'" + message + "')]";
	   WebElement actionMsg = driver.findElement(By.xpath(path));
	   Assert.assertNotNull(actionMsg);
	   
	   // close popup dialog
	   WebElement OK = driver.findElement(By.xpath("//div[contains(@id,'messagebox')]/a[1]"));
	   OK.click();
   }
   
}
